/*
Contains the AI definitions, and all variables/procs related to AI
*/

monster

	level = 1

	attack_delay = 1
	move_delay	 = 1

	var
		wander_delay 		= 1

		sleeping			= 1

		turf/last_known_loc = null
		obj/hiding_spot

		role				= MELEE
		state				= NORMAL

		see_range			= 10

	proc/ai()

		if(hp.at_min())
			sleeping = 1
			return

		attack_delay -= 1
		move_delay -= 1
		wander_delay -= 1

		switch(state)
			if(CALM)
				state = NORMAL
				//TODO: slow down, possible stop,

			if(ANGRY)
				//TODO: make me angry
				state=NORMAL

			if(HAPPY)
				if(wander_delay <= 0)

					var/player/p = locate(/player) in range(see_range+5, src)

					if(!p)

						sleeping = 1
						return

					step_rand(src)
					wander_delay = 10

			if(HIDE)
				if(!hiding_spots.len) state = FLEE

				if(!hiding_spot)

					var/list/l = list()
					for(var/obj/overlay/hiding_spot/h in oview(15, src))
						l += h

					if(!l.len) state = FLEE

					else hiding_spot = pick(l)

				if(move_delay<=0)

					if(!step_to(src, hiding_spot))

						step_towards(src, hiding_spot)

					move_delay = 2

			if(FLEE)
				call_for_help()
				if(move_delay <= 0)

					if(target)

						step_away(src,target)
						move_delay = 3

					else
						state = NORMAL

			if(NORMAL)
				if(target || last_known_loc)

					if(get_dist(src, target) > 1 || (!target && last_known_loc))

						if(move_delay <= 0)

							if(target in view(see_range, src))
								step_to(src, target)
								last_known_loc = target.loc
								move_delay = 2

							else

								if(last_known_loc)

									if(loc != last_known_loc)
										step_to(src, last_known_loc)
										move_delay = 4

									else
										step_rand(src)
										target = null
										last_known_loc = null
										move_delay = 4

								else
									target = null
									move_delay = 1

					else
						if(target.hp.at_min())
							state = HAPPY
							target = null

						if(target && attack_delay <= 0)
							attack(target)
							attack_delay = 10

					if(hp.less_than_percent(10))
						state = HIDE

				else

					get_target()

					if(target)
						sleep(5)

					else

						if(wander_delay <= 0)

							var/player/p = locate(/player) in range(see_range+5, src)

							if(!p)

								sleeping = 1
								return

							step_rand(src)
							wander_delay = 15

		spawn(2) ai()

	target(mob/m)
		target = m

	take_damage(mob/hitter, damage, color)
		..(hitter, damage, color)

		if(hitter!=target)
			target(hitter)

		state = ANGRY

	proc
		call_for_help()

			for(var/monster/m in oview(range/2, src))

				if(m.alliance & alliance)

					m.target(target)

		get_target()
			for(var/mob/m in oview(see_range, src))
				if(!(m.alliance & alliance) && m.hp && !m.hp.at_min() && !target)
					target(m)
					return